package com.qsmx.core.webfile;

import android.annotation.SuppressLint;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;

import androidx.annotation.Nullable;

import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebView;

import com.orhanobut.dialogplus.DialogPlus;
import com.qsmx.core.app.Atmos;
import com.qsmx.core.app.ConfigKeys;
import com.qsmx.core.delegates.AtmosDelegate;
import com.qsmx.core.fusion.FusionCode;
import com.qsmx.core.util.StringUtil;
import com.qsmx.core.util.log.AtmosLogger;
import com.qsmx.core.webfile.route.RouteKeys;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.lang.ref.ReferenceQueue;
import java.lang.ref.WeakReference;

/**
 * @ClassName: WebDeleage
 * @Description: java类作用描述
 * @Author: Jove.Nan
 * @Date: 2019/3/22 2:50 PM
 */
public abstract class WebDelegate extends AtmosDelegate implements IWebViewInitializer {

    private ValueCallback<Uri> mUploadMsg;
    private ValueCallback<Uri[]> mUploadMsgs;
    private DialogPlus mDialog;
    private Uri tmpFileUri;                 //当前存储的临时文件uri
    private static final int REQ_CODE_TAKE_PHOTO = 0x11;//照相
    private static final int REQ_CODE_PICK_PHOTO = 0x22;//从相册选择
    private static final int REQ_CODE_CROP_PHOTO = 0x33;//图片裁剪
    private FileWebView mWebView = null;
    private final ReferenceQueue<WebView> WEB_VIEW_QUEUE = new ReferenceQueue<>();
    private String mUrl = null;
    private String mFrom = null;
    private boolean isFromHome;
    private boolean mIsWebViewAvailable = false;
    private AtmosDelegate mTopDelegate = null;
    File imageTmpFile = null;
    private String cameraPath;
    private int checkTimes = 0;
    private boolean isShareImg = false;
    private boolean isOldShareImg = false;

    private String imgUrl;
    private Bitmap bitmap;

    public WebDelegate() {

    }

    public abstract IWebViewInitializer setInitializer();

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        final Bundle args = getArguments();
        mUrl = args.getString(RouteKeys.URL.name());
        mFrom = args.getString(FusionCode.WEB_FROM);
        isFromHome = args.getBoolean(FusionCode.WEB_HAS_NO_TITLE);
        initWebView();

    }

    @SuppressLint("JavascriptInterface")
    private void initWebView() {
        if (mWebView != null) {
            mWebView.removeAllViews();
            mWebView.destroy();
        } else {
            final IWebViewInitializer initializer = setInitializer();
            if (initializer != null) {
                final WeakReference<FileWebView> webViewWeakReference =
                        new WeakReference<>(new FileWebView(getContext(), initializer.initWebChromeClient()), WEB_VIEW_QUEUE);
                mWebView = webViewWeakReference.get();
                mWebView = initializer.initWebView(mWebView, getContext());
                mWebView.setWebViewClient(initializer.initWebViewClient());

                final String name = Atmos.getConfiguration(ConfigKeys.JAVASCRIPT_INTERFACE);
                mWebView.addJavascriptInterface(AtmosWebInterface.create(this, isFromHome), name);

                mIsWebViewAvailable = true;
            } else {
                throw new NullPointerException("Initializer is null");
            }
        }

        mWebView.setOpenFileChooserCallBack(new FileWebChromeClient.OpenFileChooserCallBack() {
            @Override
            public void openFileChooserCallBack(ValueCallback<Uri> uploadMsg, String acceptType) {
                mUploadMsg = uploadMsg;
            }

            @Override
            public void showFileChooserCallBack(ValueCallback<Uri[]> filePathCallback, WebChromeClient.FileChooserParams fileChooserParams) {
                if (mUploadMsgs != null) {
                    mUploadMsgs.onReceiveValue(null);
                }
                mUploadMsgs = filePathCallback;
                if (StringUtil.isEmpty(mFrom)) {
//                    initServerPer(getString(R.string.get_camera_service));
                }
            }
        });
    }

    public void setTopDelegate(AtmosDelegate delegate) {
        mTopDelegate = delegate;
    }

    public AtmosDelegate getTopDelegate() {
        if (mTopDelegate == null) {
            mTopDelegate = this;
        }
        return mTopDelegate;
    }

    public FileWebView getWebView() {
        if (mWebView == null) {
            throw new NullPointerException("webView is NULL");
        }
        return mIsWebViewAvailable ? mWebView : null;
    }

    public String getUrl() {
        if (mUrl == null) {
            throw new NullPointerException("url is NULL");
        }

        return mUrl;
    }

    @Override
    public void onPause() {
        super.onPause();
        if (mWebView != null) {
            mWebView.onPause();
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        if (mWebView != null) {
            mWebView.onResume();
            mWebView.evaluateJavascript("shareFun('1')", new ValueCallback<String>() {
                @Override
                public void onReceiveValue(String value) {
                    AtmosLogger.e("webView", value);
                }
            });
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        mIsWebViewAvailable = false;
        EventBus.getDefault().unregister(this);
    }


    @Override
    public boolean onBackPressedSupport() {
        if (mWebView.canGoBack()) {
            mWebView.goBack();
        } else {
            getParentDelegate().getSupportDelegate().pop();
        }
        return true;
    }

//    @NeedsPermission({Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA})
//    void startCheckPhoto() {
//        if (isShareImg) {
//            isShareImg = false;
//            returnBitMap(imgUrl);
//        } else if (isOldShareImg) {
//            isOldShareImg = false;
//            saveImageToGallery(getContext(), bitmap, "cut_");
//        } else {
//            showTakePhotoDialog();
//        }
//    }
//
//    @OnShowRationale({Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA})
//    void onCheckPhotoRational(PermissionRequest request) {
//        showRationalDialog(R.string.write_and_read_external_storage, request);
//    }
//
//    @Override
//    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
//        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
//        WebDelegatePermissionsDispatcher.onRequestPermissionsResult(this, requestCode, grantResults);
//    }
//
//    private void initServerPer(String permissTips) {
//        String[] permissions = {Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA};
//        if (checkPermissionAllGranted(permissions)) {
//            WebDelegatePermissionsDispatcher.startCheckPhotoWithCheck(this);
//        } else {
//            DialogUtil.showPromptDialog(getContext(), getString(R.string.tips), permissTips, "同意授权", "拒绝授权",
//                    new SweetAlertDialog.OnSweetClickListener() {
//                        @Override
//                        public void onClick(SweetAlertDialog sweetAlertDialog) {
//                            showLongToast("已拒绝授权");
//                            sweetAlertDialog.dismissWithAnimation();
//                        }
//                    }, new SweetAlertDialog.OnSweetClickListener() {
//                        @Override
//                        public void onClick(SweetAlertDialog sweetAlertDialog) {
//                            sweetAlertDialog.dismissWithAnimation();
//                            WebDelegatePermissionsDispatcher.startCheckPhotoWithCheck(WebDelegate.this);
//                        }
//                    });
//        }
//    }
//
//    private void showTakePhotoDialog() {
//
//        mDialog = DialogPlus.newDialog(getProxyActivity())
//                .setContentHolder(new ViewHolder(R.layout.send_dynamic_view))
//                .setOnCancelListener(new OnCancelListener() {
//                    @Override
//                    public void onCancel(DialogPlus dialog) {
//                        if (mUploadMsgs != null) {
//                            mUploadMsgs.onReceiveValue(null);
//                            mUploadMsgs = null;
//                        }
//                    }
//                }).create();
//        View view = mDialog.getHolderView();
//
//        view.findViewById(R.id.cancel_btn).setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                mDialog.dismiss();
//                if (mUploadMsgs != null) {
//                    mUploadMsgs.onReceiveValue(null);
//                    mUploadMsgs = null;
//                }
//            }
//        });
//        view.findViewById(R.id.camer_text).setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                takePhotoFromCamera();
//            }
//        });
//        view.findViewById(R.id.album_text).setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                takePhotoFromPick();
//            }
//        });
//        view.findViewById(R.id.video_text).setVisibility(View.GONE);
//
//        mDialog.show();
//    }
//
//    /**
//     * 从相机获取照片
//     */
//    private void takePhotoFromCamera() {
//        mDialog.dismiss();
//        String path = getContext().getExternalFilesDir("").getAbsolutePath() + "/qgy/cache/video/";
//        Intent openCameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
//
//        if (openCameraIntent.resolveActivity(getActivity().getPackageManager()) != null) {
//            File cameraFile = PictureFileUtils.createCameraFile(getContext(), PictureConfig.TYPE_IMAGE, path, ".png");
//            cameraPath = cameraFile.getAbsolutePath();
//            Uri imageUri = parUri(cameraFile);
//            openCameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
//            startActivityForResult(openCameraIntent, REQ_CODE_TAKE_PHOTO);
//        }
//
////        //生成临时文件，用于相机拍出来的文件存储
////        String tmpFileName = CommonUtils.generateFileName(FusionCode.FileType.FILE_TYPE_IMAGE);
////        try {
////            imageTmpFile = CommonUtils.getAppTmpFile(tmpFileName, getContext());
////            if (imageTmpFile == null) {
////                Toast.makeText(getContext(), "文件创建失败", Toast.LENGTH_SHORT).show();
////                return;
////            }
////            //获取临时文件uri
////            tmpFileUri = Uri.fromFile(imageTmpFile);
////            //设置相机图片输出uri
////            openCameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, tmpFileUri);
////            startActivityForResult(openCameraIntent, REQ_CODE_TAKE_PHOTO);
////        } catch (Exception e) {
////            Log.e("takePhoto", e.getMessage(), e);
////            Toast.makeText(getContext(), "未检测到sdcard，请先插入sdcard", Toast.LENGTH_SHORT).show();
////        }
//    }
//
//    /**
//     * 从相册获取照片
//     */
//    private void takePhotoFromPick() {
//        mDialog.dismiss();
//        Intent pictureIntent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
//        pictureIntent.setType("image/*");
//        startActivityForResult(pictureIntent, REQ_CODE_PICK_PHOTO);
//    }
//
//    /**
//     * 生成uri
//     *
//     * @param cameraFile
//     * @return
//     */
//    private Uri parUri(File cameraFile) {
//        Uri imageUri;
//        String authority = getActivity().getPackageName() + ".provider";
//        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.M) {
//            //通过FileProvider创建一个content类型的Uri
//            imageUri = FileProvider.getUriForFile(getContext(), authority, cameraFile);
//        } else {
//            imageUri = Uri.fromFile(cameraFile);
//        }
//        return imageUri;
//    }
//
//    /*
//        处理从相机获取的图片
//     */
//    private void processTakePhoto() {
//
//        if (StringUtil.isNotEmpty(cameraPath)) {
//            File imageTmpFiles = new File(cameraPath);
//
//            final Uri imageUri = Uri.fromFile(imageTmpFiles);
//            if (mUploadMsg != null) {
//                mUploadMsg.onReceiveValue(Uri.parse(imageUri.getPath()));
//                mUploadMsg = null;
//            }
//            if (mUploadMsgs != null) {
//                mUploadMsgs.onReceiveValue(new Uri[]{imageUri});
//                mUploadMsgs = null;
//            }
//        } else {
//            if (mUploadMsgs != null) {
//                mUploadMsgs.onReceiveValue(null);
//                mUploadMsgs = null;
//            }
//        }
//    }
//
//    /*
//        处理从相册获取的图片
//     */
//    private void processPickPhoto(Intent data) {
//        //通过content resolver 来获取bitmap对象
//        if (data != null) {
//            final Uri imageUri = data.getData();
//            if (mUploadMsg != null) {
//                mUploadMsg.onReceiveValue(Uri.parse(imageUri.getPath()));
//                mUploadMsg = null;
//            }
//            if (mUploadMsgs != null) {
//                mUploadMsgs.onReceiveValue(new Uri[]{imageUri});
//                mUploadMsgs = null;
//            }
//        } else {
//            if (mUploadMsgs != null) {
//                mUploadMsgs.onReceiveValue(null);
//                mUploadMsgs = null;
//            }
//        }
//    }
//
//    private void checkRewardIsReceive(String extend) {
//        JSONObject params = new JSONObject();
//        params.put("extend", extend);
//
//        checkTimes += 1;
//        HttpHelper.RestClientPostRaw(params, HttpUrl.QUERY_REWARD_RECEIVED,
//                new ISuccess() {
//                    @Override
//                    public void onSuccess(String response) {
//                        Type type = new TypeToken<ReceiveRewardEntity>() {
//                        }.getType();
//                        Gson gson = new Gson();
//                        ReceiveRewardEntity mData = gson.fromJson(response, type);
//                        if (mData.getHeader().getCode() == 0) {
//                            checkTimes = 0;
//                            mWebView.evaluateJavascript("receiveVideoReward()", new ValueCallback<String>() {
//                                @Override
//                                public void onReceiveValue(String value) {
//                                    AtmosLogger.e("webView", value);
//                                }
//                            });
//                        } else {
//                            if (checkTimes <= 10) {
//                                checkRewardIsReceive(extend);
//                            }
//                        }
//                    }
//                }, new IError() {
//                    @Override
//                    public void onError(int code, String msg) {
//                        if (checkTimes <= 10) {
//                            checkRewardIsReceive(extend);
//                        }
//                    }
//                }, new IFailure() {
//                    @Override
//                    public void onFailure() {
//                        if (checkTimes <= 10) {
//                            checkRewardIsReceive(extend);
//                        }
//                    }
//                });
//    }
//
//    public void gotoNewSaveImage(String imgUrl) {
//        isShareImg = true;
//        this.imgUrl = imgUrl;
//        initServerPer(getString(R.string.get_camera_save));
////        WebDelegatePermissionsDispatcher.startCheckPhotoWithCheck(this);
//    }
//
//    public void gotoSaveImage(Bitmap img) {
//        isOldShareImg = true;
//        this.bitmap = img;
//        initServerPer(getString(R.string.get_camera_save));
//
////        WebDelegatePermissionsDispatcher.startCheckPhotoWithCheck(this);
//    }
//
//    public void returnBitMap(final String url) {
//        showProgressDialog("请稍后...");
//        new Thread(new Runnable() {
//            @Override
//            public void run() {
//                URL imageurl = null;
//
//                try {
//                    imageurl = new URL(url);
//                } catch (MalformedURLException e) {
//                    e.printStackTrace();
//                }
//                try {
//                    HttpURLConnection conn = (HttpURLConnection) imageurl.openConnection();
//                    conn.setDoInput(true);
//                    conn.connect();
//                    InputStream is = conn.getInputStream();
//                    Bitmap bitmap = BitmapFactory.decodeStream(is);
//                    is.close();
//
//                    getProxyActivity().runOnUiThread(new Runnable() {
//                        @Override
//                        public void run() {
//                            saveImageToGallery(getContext(), bitmap, "cut_");
//                        }
//                    });
//
//                } catch (IOException e) {
//                    e.printStackTrace();
//                }
//            }
//        }).start();
//    }
//
//    /**
//     * 保存图片到指定路径
//     *
//     * @param context
//     * @param *bitmap  要保存的图片
//     * @param fileName 自定义图片名称
//     */
//    public void saveImageToGallery(Context context, Bitmap bitmap, String fileName) {
//        DateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
//        fileName = fileName + format.format(new Date()) + ".png";
//        // 保存图片至指定路径
//        String storePath = getProxyActivity().getExternalFilesDir(null).getPath() + "/share/";
//        File appDir = new File(storePath);
//        if (!appDir.exists()) {
//            appDir.mkdir();
//        }
//        File file = new File(appDir, fileName);
//        try {
//            FileOutputStream fos = new FileOutputStream(file);
//            //通过io流的方式来压缩保存图片(80代表压缩20%)
//            boolean isSuccess = bitmap.compress(Bitmap.CompressFormat.PNG, 80, fos);
//            fos.flush();
//            fos.close();
//            // 其次把文件插入到系统图库
////            try {
////                MediaStore.Images.Media.insertImage(context.getContentResolver(), file.getAbsolutePath(), fileName, null);
////            } catch (FileNotFoundException e) {
////                e.printStackTrace();
////            }
//            //发送广播通知系统图库刷新数据
//            System.out.println("发送广播通知系统图库刷新数据");
//            Uri uri = Uri.fromFile(file);
//            context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, uri));
//
//            if (isSuccess) {
////                Toast.makeText(context, "图片已保存至" + file, Toast.LENGTH_SHORT).show();
//                new Thread(new Runnable() {
//                    @Override
//                    public void run() {
//                        try {
//                            Thread.sleep(500);
//                            getProxyActivity().runOnUiThread(new Runnable() {
//                                @Override
//                                public void run() {
//                                    removeProgressDialog();
//                                    ShareManager.showShareDialog(getContext(), getProxyActivity(), BitmapFactory.decodeFile(file.getPath()), file.getPath());
//                                }
//                            });
//                        } catch (InterruptedException e) {
//                            e.printStackTrace();
//                        }
//                    }
//                }).start();
//            } else {
//                removeProgressDialog();
////                Toast.makeText(context, "图片保存失败", Toast.LENGTH_SHORT).show();
//            }
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//    }
//
//
//    @Override
//    public void onActivityResult(int requestCode, int resultCode, Intent data) {
//        super.onActivityResult(requestCode, resultCode, data);
//        if (requestCode == REQ_CODE_TAKE_PHOTO) {
//            processTakePhoto();
//        } else if (requestCode == REQ_CODE_PICK_PHOTO) {
//            processPickPhoto(data);
//        }
//    }
//
//    @Subscribe(threadMode = ThreadMode.MAIN)
//    public void onMessageEvent(LoginEvent event) {
//        if (event != null && event.getData() != null) {
//            mWebView.evaluateJavascript("getNewToken('" + AtmosPreference.getCustomStringPre(PrefConst.TOKEN) + "')", new ValueCallback<String>() {
//                @Override
//                public void onReceiveValue(String value) {
//                    AtmosLogger.e("webView", value);
//                }
//            });
//        }
//    }
//
//    @Subscribe(threadMode = ThreadMode.MAIN)
//    public void onMessageEvent(RewardFinishEvent event) {
//        if (event != null && event.getData() != null) {
//            checkRewardIsReceive(event.getData().getString("extend"));
//        }
//    }
//
//
//    @Subscribe(threadMode = ThreadMode.MAIN)
//    public void onMessageEvent(PayStartEvent event) {
//        if (event != null && event.getData() != null) {
//            mWebView.evaluateJavascript("backPayStatus('1')", new ValueCallback<String>() {
//                @Override
//                public void onReceiveValue(String value) {
//                    AtmosLogger.e("webView", value);
//                }
//            });
//        }
//    }
//
//    @Subscribe(threadMode = ThreadMode.MAIN)
//    public void onMessageEvent(H5QrRefreshEvent event) {
//        if (event != null && event.getData() != null) {
//            mWebView.evaluateJavascript("getNewDopInfo(\"" + event.getData().getString("resultString") + "\")", new ValueCallback<String>() {
//                @Override
//                public void onReceiveValue(String value) {
//                    AtmosLogger.e("webView", value);
//                }
//            });
//        }
//    }

    @Override
    public void onStart() {
        super.onStart();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mWebView != null) {
            mWebView.removeAllViews();
            mWebView.destroy();
            mWebView = null;
        }
    }
}
